import Mock from 'mockjs'

// 生成贷款列表
const generateLoans = (userId, count = 5) => {
    const list = [];
    const statusMap = {
        0: '申请中',
        1: '审核中',
        2: '已拒绝',
        3: '已通过',
        4: '已放款',
        5: '还款中',
        6: '已结清',
        7: '已逾期'
    };
    
    for (let i = 0; i < count; i++) {
        const status = Mock.Random.integer(0, 7);
        const amount = Mock.Random.integer(5000, 100000);
        const period = Mock.Random.integer(3, 36);
        const interestRate = Mock.Random.float(4.8, 12, 2, 2);
        
        const applyTime = Mock.Random.datetime();
        let approveTime = null;
        let loanTime = null;
        let repayStartTime = null;
        let repayEndTime = null;
        
        if (status >= 1) {
            approveTime = Mock.Random.datetime();
        }
        
        if (status >= 3) {
            loanTime = Mock.Random.datetime();
        }
        
        if (status >= 4) {
            repayStartTime = Mock.Random.datetime();
            
            if (status === 6) {
                repayEndTime = Mock.Random.datetime();
            }
        }
        
        list.push({
            id: i + 1,
            userId,
            loanNo: `LOAN${Mock.Random.string('number', 10)}`,
            amount,
            period,
            interestRate,
            purpose: Mock.Random.pick(['购房', '购车', '装修', '教育', '旅游', '医疗', '其他']),
            status,
            statusText: statusMap[status],
            applyTime,
            approveTime,
            loanTime,
            repayStartTime,
            repayEndTime,
            bankCardId: Mock.Random.integer(1, 3),
            createTime: Mock.Random.datetime(),
            updateTime: Mock.Random.datetime()
        });
    }
    
    return list;
};

// 生成贷款产品列表
const generateLoanProducts = (count = 3) => {
    const list = [];
    
    const products = [
        {
            name: '小额贷款',
            minAmount: 5000,
            maxAmount: 50000,
            minPeriod: 3,
            maxPeriod: 12,
            interestRate: 8.8,
            description: '适合短期资金需求，最快1小时放款，灵活还款方式'
        },
        {
            name: '个人信用贷款',
            minAmount: 50000,
            maxAmount: 300000,
            minPeriod: 6,
            maxPeriod: 36,
            interestRate: 6.8,
            description: '无需抵押担保，利率低至4.8%，期限最长36个月'
        },
        {
            name: '大额贷款',
            minAmount: 300000,
            maxAmount: 1000000,
            minPeriod: 12,
            maxPeriod: 60,
            interestRate: 4.8,
            description: '满足大额资金需求，还款期限更长，专属客户经理服务'
        }
    ];
    
    for (let i = 0; i < count; i++) {
        list.push({
            id: i + 1,
            ...products[i],
            createTime: Mock.Random.datetime(),
            updateTime: Mock.Random.datetime()
        });
    }
    
    return list;
};

// 模拟数据
export default {
    // 获取贷款列表接口
    '/api/loans/user/\\d+ get': (options) => {
        const userId = parseInt(options.url.match(/\/api\/loans\/user\/(\d+)/)[1]);
        return {
            code: 200,
            msg: '获取成功',
            data: generateLoans(userId)
        };
    },
    
    // 获取贷款详情接口
    '/api/loans/\\d+ get': (options) => {
        const id = parseInt(options.url.match(/\/api\/loans\/(\d+)/)[1]);
        const loans = generateLoans(1, 10);
        const loan = loans.find(item => item.id === id) || loans[0];
        
        return {
            code: 200,
            msg: '获取成功',
            data: loan
        };
    },
    
    // 申请贷款接口
    '/api/loans/apply post': (options) => {
        const data = JSON.parse(options.body);
        return {
            code: 200,
            msg: '申请成功',
            data: {
                id: Mock.Random.integer(1, 100),
                userId: data.userId,
                loanNo: `LOAN${Mock.Random.string('number', 10)}`,
                amount: data.amount,
                period: data.period,
                interestRate: data.interestRate,
                purpose: data.purpose,
                status: 0,
                statusText: '申请中',
                applyTime: Mock.Random.datetime(),
                bankCardId: data.bankCardId,
                createTime: Mock.Random.datetime(),
                updateTime: Mock.Random.datetime()
            }
        };
    },
    
    // 取消贷款申请接口
    '/api/loans/\\d+/cancel put': () => {
        return {
            code: 200,
            msg: '取消成功',
            data: null
        };
    },
    
    // 获取贷款产品列表接口
    '/api/loan-products get': () => {
        return {
            code: 200,
            msg: '获取成功',
            data: generateLoanProducts()
        };
    },
    
    // 获取贷款产品详情接口
    '/api/loan-products/\\d+ get': (options) => {
        const id = parseInt(options.url.match(/\/api\/loan-products\/(\d+)/)[1]);
        const products = generateLoanProducts();
        const product = products.find(item => item.id === id) || products[0];
        
        return {
            code: 200,
            msg: '获取成功',
            data: product
        };
    },
    
    // 计算贷款接口
    '/api/loans/calculate post': (options) => {
        const data = JSON.parse(options.body);
        const { amount, period, interestRate } = data;
        
        // 计算月供
        const monthlyInterestRate = interestRate / 100 / 12;
        const monthlyPayment = amount * monthlyInterestRate * Math.pow(1 + monthlyInterestRate, period) / (Math.pow(1 + monthlyInterestRate, period) - 1);
        const totalPayment = monthlyPayment * period;
        const totalInterest = totalPayment - amount;
        
        // 生成还款计划
        const repaymentPlan = [];
        let remainingPrincipal = amount;
        
        for (let i = 1; i <= period; i++) {
            const interest = remainingPrincipal * monthlyInterestRate;
            const principal = monthlyPayment - interest;
            remainingPrincipal -= principal;
            
            repaymentPlan.push({
                period: i,
                amount: Math.round(monthlyPayment * 100) / 100,
                principal: Math.round(principal * 100) / 100,
                interest: Math.round(interest * 100) / 100,
                remainingPrincipal: Math.round(remainingPrincipal * 100) / 100
            });
        }
        
        return {
            code: 200,
            msg: '计算成功',
            data: {
                amount,
                period,
                interestRate,
                monthlyPayment: Math.round(monthlyPayment * 100) / 100,
                totalPayment: Math.round(totalPayment * 100) / 100,
                totalInterest: Math.round(totalInterest * 100) / 100,
                repaymentPlan
            }
        };
    }
};